﻿namespace SSE_Client
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            var cts = new CancellationTokenSource();

            // 启动一个任务来监听取消操作
            _ = Task.Run(() =>
            {
                Console.WriteLine("Press Enter to stop...");
                Console.ReadLine();
                cts.Cancel();
            });

            var url = "http://localhost:5133/SSE/Stream"; // SSE 端点
            using var httpClient = new HttpClient();

            try
            {
                // 发送 GET 请求
                using var response = await httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cts.Token);
                response.EnsureSuccessStatusCode();

                // 获取响应流
                using var stream = await response.Content.ReadAsStreamAsync();
                using var reader = new StreamReader(stream);

                // 读取事件流
                while (!reader.EndOfStream)
                {
                    var line = await reader.ReadLineAsync();
                    if (string.IsNullOrEmpty(line)) continue; // 忽略空行

                    if (line.StartsWith("data:"))
                    {
                        // 提取数据
                        var data = line.Substring("data:".Length).Trim();
                        Console.WriteLine($"Received: {data}");
                    }
                    else if (line.StartsWith("event:"))
                    {
                        // 处理自定义事件类型
                        var eventType = line.Substring("event:".Length).Trim();
                        Console.WriteLine($"Event type: {eventType}");
                    }
                    else if (line.StartsWith("id:"))
                    {
                        // 处理事件 ID
                        var eventId = line.Substring("id:".Length).Trim();
                        Console.WriteLine($"Event ID: {eventId}");
                    }
                }
            }
            catch (OperationCanceledException)
            {
                Console.WriteLine("Operation canceled.");
            }

            Console.WriteLine("Stream ended.");
        }
    }
}
